<template>
  <div class="home-page">
    <!-- 顶部欢迎区 -->
    <div class="welcome-section">
      <div class="welcome-left">
        <i class="welcome-icon">👋</i>
        <span>欢迎回来，{{ userName }}</span>
      </div>
      <div class="welcome-right">
        <span class="more-link">查看更多 <i class="el-icon-arrow-right"></i></span>
      </div>
    </div>

    <!-- 主要统计区域 -->
    <div class="main-stats-container">
      <div class="stats-cards">
        <div v-for="item in stats" :key="item.title" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :class="item.iconClass">
              <i class="stat-icon-inner">{{ item.icon }}</i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ item.value }} <span class="stat-unit">{{ item.unit }}</span></div>
              <div class="stat-title">{{ item.title }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 检索次数区域 -->
      <div class="search-stats-container">
        <div class="search-stats-header">
          <span class="search-stats-title">检测次数</span>
          <div class="search-stats-toggle">
            <el-radio-group v-model="activeRange" size="small">
              <el-radio-button label="7days">近7日</el-radio-button>
              <el-radio-button label="30days">近30日</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div ref="barChartRef" class="bar-chart"></div>
      </div>
    </div>

    <!-- 底部两个卡片 -->
    <div class="bottom-row">
      <div class="chart-card">
        <div class="chart-header">
          <span class="chart-title">情绪分布</span>
          <el-dropdown size="small">
            <span class="chart-dropdown-link">
              本月 <i class="el-icon-arrow-down"></i>
            </span>
          </el-dropdown>
        </div>
        <div ref="emotionPieRef" class="pie-chart"></div>
      </div>
      <div class="chart-card">
        <div class="chart-header">
          <span class="chart-title">用户今日检测情况</span>
        </div>
        <div ref="userPieRef" class="pie-chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'

const userName = ref(localStorage.getItem('user') || 'Administrator')
const totalUserCount = ref(0)
const totalRecordCount = ref(0)
const recordList = ref([])
const last7DaysRecords = ref([])
const last30DaysRecords = ref([])
const loginLogs = ref([])
const todayActiveUserCount = ref(0)
// 获取今日日期
function getToday() {
  const now = new Date()
  const yyyy = now.getFullYear()
  const mm = String(now.getMonth() + 1).padStart(2, '0')
  const dd = String(now.getDate()).padStart(2, '0')
  return `${yyyy}-${mm}-${dd}`
}
// 计算日期差（天数）
function dateDiff(date1, date2) {
  const d1 = new Date(date1)
  const d2 = new Date(date2)
  return Math.floor((d1 - d2) / (1000 * 60 * 60 * 24))
}
function getRecentDays(days) {
  const arr = []
  const now = new Date()
  for (let i = days - 1; i >= 0; i--) {
    const d = new Date(now)
    d.setDate(now.getDate() - i)
    arr.push(d.toISOString().slice(0, 10))
  }
  return arr
}
function getRecent5DayRanges() {
  const now = new Date()
  const ranges = []
  for (let i = 5; i <= 30; i += 5) {
    const end = new Date(now)
    end.setDate(now.getDate() - (i - 5))
    const start = new Date(now)
    start.setDate(now.getDate() - i + 1)
    ranges.push({
      label: `${start.toISOString().slice(0, 10)}~${end.toISOString().slice(0, 10)}`,
      start: start.toISOString().slice(0, 10),
      end: end.toISOString().slice(0, 10)
    })
  }
  return ranges.reverse()
}
function formatMMDD(dateStr) {
  const d = new Date(dateStr)
  const mm = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  return `${mm}/${dd}`
}
// 获取总用户数
const fetchUserCount = async () => {
  try {
    const res = await axios.get('http://localhost:8181/user/list?currentPage=1&pageSize=10', {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (res.data.code === 200) {
      totalUserCount.value = res.data.data.total || 0
    }
  } catch (e) {
    totalUserCount.value = 0
  }
}

// 获取总检测数及日期
const fetchRecordCount = async () => {
  try {
    const res = await axios.get('http://localhost:8181/uploadRecord/getRecordList', {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (res.data.code === 200 && Array.isArray(res.data.data)) {
      // 处理每条记录，提取uploadTime、uploadDate、emotionType
      const list = res.data.data.map(item => ({
        uploadTime: item.uploadTime,
        uploadDate: item.uploadTime ? item.uploadTime.slice(0, 10) : '',
        emotionType: item.emotionType
      }))
      // 按时间倒序
      list.sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime))
      recordList.value = list
      totalRecordCount.value = list.length

      // 计算近7天和近30天的记录
      const today = getToday()
      last7DaysRecords.value = list.filter(item => {
        if (!item.uploadDate) return false
        return dateDiff(today, item.uploadDate) < 7 && dateDiff(today, item.uploadDate) >= 0
      })
      last30DaysRecords.value = list.filter(item => {
        if (!item.uploadDate) return false
        return dateDiff(today, item.uploadDate) < 30 && dateDiff(today, item.uploadDate) >= 0
      })
      nextTick(() => {
        renderBarChart()
        renderPieCharts()
      })
    }
  } catch (e) {
    totalRecordCount.value = 0
    recordList.value = []
    last7DaysRecords.value = []
    last30DaysRecords.value = []
  }
}

// 时间戳转 yyyy-mm-dd
function formatDateFromTimestamp(ts) {
  const d = new Date(ts * 1000)
  const yyyy = d.getFullYear()
  const mm = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  return `${yyyy}-${mm}-${dd}`
}
// 获取所有登录日志（分页）
const fetchAllLoginLogs = async () => {
  let page = 1
  let totalPages = 1
  let allLogs = []
  try {
    // 先查第一页，拿到总页数
    const firstRes = await axios.get('http://localhost:8181/login-logs/loginLog/list', {
      params: { currentPage: page, pageSize: 100 },
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (firstRes.data.code === 200 && firstRes.data.data) {
      totalPages = firstRes.data.data.pages
      allLogs = firstRes.data.data.records.map(item => ({
        userId: item.userId,
        loginTime: item.loginTime
      }))
    }
    console.log(totalPages.value);
    // 继续查剩余页
    for (let p = 2; p <= totalPages; p++) {
      const res = await axios.get('http://localhost:8181/login-logs/loginLog/list', {
        params: { currentPage: p, pageSize: 100 },
        headers: {
          [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
        }
      })
      if (res.data.code === 200 && res.data.data) {
        allLogs = allLogs.concat(
          res.data.data.records.map(item => ({
            userId: item.userId,
            loginTime: item.loginTime
          }))
        )
      }
    }
    loginLogs.value = allLogs
    // 统计今日活跃用户数
    const today = getToday()
    const todayUserSet = new Set()
    allLogs.forEach(log => {
      if (formatDateFromTimestamp(log.loginTime) === today) {
        todayUserSet.add(log.userId)
      }
    })
    todayActiveUserCount.value = todayUserSet.size
  } catch (e) {
    loginLogs.value = []
    todayActiveUserCount.value = 0
  }
}

function updateChartData() {
  // 近7天每天
  const days7 = getRecentDays(7)
  chartData.value.last7 = days7.map(day => ({
    date: formatMMDD(day),
    count: last7DaysRecords.value.filter(item => item.uploadDate === day).length
  }))
  // 近30天每5天
  const ranges = getRecent5DayRanges()
  chartData.value.last30 = ranges.map(range => ({
    date: `${formatMMDD(range.start)}~${formatMMDD(range.end)}`,
    count: last30DaysRecords.value.filter(item =>
      item.uploadDate >= range.start && item.uploadDate <= range.end
    ).length
  }))
}

const stats = computed(() => [
  { icon: '📊', iconClass: 'icon-blue', title: '总用户数', value: totalUserCount.value, unit: '个' },
  { icon: '📝', iconClass: 'icon-purple', title: '总检测数', value: totalRecordCount.value, unit: '个' },
  { icon: '👥', iconClass: 'icon-orange', title: '日活用户', value: todayActiveUserCount.value, unit: '个' },
  {
    icon: '📈',
    iconClass: 'icon-green',
    title: '活跃日活率',
    value: totalUserCount.value > 0
      ? ((todayActiveUserCount.value / totalUserCount.value) * 100).toFixed(2)
      : '0.00',
    unit: '%'
  }
])

// 柱状图
const barChartRef = ref(null)
const activeRange = ref('7days') // 当前选中的时间范围
const chartData = ref({
  last7: [],
  last30: []
})

let barChart = null

// 情绪分布饼图
const emotionPieRef = ref(null)
const emotionTranslations = {
  'angry': '愤怒',
  'disgust': '厌恶',
  'surprise': '惊喜',
  'happy': '开心',
  'fear': '恐惧',
  'sad': '悲伤',
  'neutral': '中性',
  'unknown': '未检测'
}
const emotionPieData = computed(() => {
  const tmp = {}
  last30DaysRecords.value.forEach(item => {
    const type = item.emotionType || 'unknown'
    tmp[type] = (tmp[type] || 0) + 1
  })
  return Object.entries(tmp).map(([key, value]) => ({
    value,
    name: emotionTranslations[key] || key
  }))
})

// 用户人数占比饼图
const userPieRef = ref(null)
const userPieData = computed(() => {
  // 统计今日检测人数
  const today = getToday()
  const todayUserSet = new Set()
  last30DaysRecords.value.forEach(item => {
    if (item.uploadDate === today) {
      todayUserSet.add(item.userId)
    }
  })
  const todayCount = todayUserSet.size
  return [
    { value: todayCount, name: '今日检测人数' },
    { value: totalUserCount.value - todayCount, name: '其他用户' },
    { value: 0, name: '未知' } // 占位
  ]
})

const renderBarChart = () => {
  if (!barChartRef.value) return

  if (barChart) {
    barChart.dispose()
  }

  barChart = echarts.init(barChartRef.value)
  const currentData = chartData.value[activeRange.value === '7days' ? 'last7' : 'last30']

  // 计算柱宽 - 根据数据量自动调整
  const barWidth = activeRange.value === '7days' ? '40%' : '60%'
  barChart.setOption({
    grid: {
      left: '5%',
      right: '5%',
      top: '10%',
      bottom: '10%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255,255,255,0.9)',
      borderColor: '#e6e6e6',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(0,0,0,0.03)'
        }
      }
    },
    xAxis: {
      type: 'category',
      data: currentData.map(item => item.date),
      axisLine: { lineStyle: { color: '#eaeaea' } },
      axisTick: { show: false },
      axisLabel: {
        color: '#888',
        fontSize: 12,
        interval: 0,
        rotate:  0
      }
    },
    yAxis: {
      type: 'value',
      minInterval: (Math.max(currentData.map(item => item.count)) + 5) / 10 * 10,
      splitLine: { lineStyle: { color: '#f2f2f2', type: 'dashed' } },
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: '#888', fontSize: 12 }
    },
    series: [{
      name: '检测量',
      type: 'bar',
      data: currentData.map(item => item.count),
      barWidth: barWidth,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#7da6fa' },
          { offset: 1, color: '#5b8ff9' }
        ]),
        borderRadius: [6, 6, 0, 0]
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#5b8ff9' },
            { offset: 0.7, color: '#7da6fa' },
            { offset: 1, color: '#83bff6' }
          ])
        }
      },
      label: {
        show: true,
        position: 'top',
        color: '#5b8ff9',
        fontWeight: 500,
        fontSize: 12,
        formatter: '{c}'
      }
    }]
  })
}

const renderPieCharts = () => {
  // 情绪分布饼图
  if (!emotionPieRef.value) return

  const emotionPie = echarts.init(emotionPieRef.value)
  emotionPie.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      backgroundColor: 'rgba(255,255,255,0.9)',
      borderColor: '#e6e6e6',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      }
    },
    legend: {
      bottom: 0,
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 12,
      textStyle: {
        color: '#666',
        fontSize: 12
      },
      selectedMode: true
    },
    series: [{
      name: '情绪分布',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '45%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 6,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 12,
          fontWeight: 'bold'
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.2)'
        }
      },
      labelLine: {
        show: false
      },
      data: emotionPieData.value,
      color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452']
    }]
  })

  // 用户人数占比饼图
  if (!userPieRef.value) return

  const userPie = echarts.init(userPieRef.value)
  userPie.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      backgroundColor: 'rgba(255,255,255,0.9)',
      borderColor: '#e6e6e6',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      }
    },
    legend: {
      bottom: 0,
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 12,
      textStyle: {
        color: '#666',
        fontSize: 12
      }
    },
    series: [{
      name: '用户人数',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '45%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 6,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 12,
          fontWeight: 'bold'
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.2)'
        }
      },
      labelLine: {
        show: false
      },
      data: userPieData.value,
      color: ['#5b8ff9', '#5ad8a6', '#5d7092']
    }]
  })

  // 窗口大小变化时重新调整图表大小
  window.addEventListener('resize', () => {
    if (barChart) barChart.resize()
    if (emotionPie) emotionPie.resize()
    if (userPie) userPie.resize()
  })
}

const switchRange = (range) => {
  activeRange.value = range
}

watch(activeRange, () => {
  nextTick(() => {
    renderBarChart()
  })
})

watch([last7DaysRecords, last30DaysRecords], updateChartData, { immediate: true })
// 页面加载时调用
onMounted(() => {
  fetchUserCount()
  fetchRecordCount()
  fetchAllLoginLogs()
  nextTick(() => {
    renderBarChart()
    renderPieCharts()
  })
})
</script>

<style scoped>
.home-page {
  padding: 24px;
  background: #f6f8fa;
  min-height: 100vh;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.welcome-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 8px;
}

.welcome-left {
  display: flex;
  align-items: center;
}

.welcome-icon {
  margin-right: 12px;
  font-size: 24px;
}

.welcome-left span {
  font-size: 20px;
  font-weight: 600;
  color: #2e3846;
}

.more-link {
  font-size: 14px;
  color: #4080ff;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
}

.more-link:hover {
  color: #699bff;
}

.more-link i {
  margin-left: 4px;
  font-size: 12px;
}

.main-stats-container {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 24px;
  transition: all 0.3s;
}

.main-stats-container:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.stats-cards {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  padding: 0;
}

.stat-card {
  flex: 1;
  padding: 12px;
  position: relative;
  transition: all 0.2s;
}

.stat-card:hover {
  background-color: #f8faff;
}

.stat-card:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 25%;
  height: 50%;
  width: 1px;
  background-color: #f0f0f0;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  transition: all 0.3s;
}

.stat-icon-inner {
  font-size: 26px;
  font-style: normal;
}

.icon-blue {
  background-color: rgba(64, 128, 255, 0.1);
  color: #4080ff;
}

.icon-purple {
  background-color: rgba(165, 94, 234, 0.1);
  color: #a55eea;
}

.icon-orange {
  background-color: rgba(250, 130, 76, 0.1);
  color: #fa824c;
}

.icon-green {
  background-color: rgba(38, 194, 129, 0.1);
  color: #26c281;
}

.stat-card:hover .stat-icon {
  transform: scale(1.05);
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #2e3846;
  line-height: 1.2;
  margin-bottom: 6px;
  letter-spacing: 0.5px;
}

.stat-unit {
  font-size: 14px;
  font-weight: normal;
  color: #8c8c8c;
  margin-left: 2px;
}

.stat-title {
  font-size: 14px;
  color: #8c8c8c;
}

.search-stats-container {
  padding: 20px 24px 30px;
}

.search-stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-stats-title {
  font-size: 16px;
  font-weight: 600;
  color: #2e3846;
}

.search-stats-toggle {
  display: flex;
  gap: 10px;
}

.bar-chart {
  width: 100%;
  height: 320px;
}

.bottom-row {
  display: flex;
  gap: 24px;
}

.chart-card {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 0;
  transition: all 0.3s;
  overflow: hidden;
}

.chart-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #2e3846;
}

.chart-dropdown-link {
  font-size: 13px;
  color: #8c8c8c;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.chart-dropdown-link i {
  margin-left: 4px;
  font-size: 12px;
}

.pie-chart {
  width: 100%;
  height: 280px;
  padding: 20px;
}

/* 响应式处理 */
@media (max-width: 1200px) {
  .bottom-row {
    gap: 16px;
  }
}

@media (max-width: 992px) {
  .stats-cards {
    flex-wrap: wrap;
  }

  .stat-card {
    flex: 1 0 50%;
  }

  .stat-card:nth-child(2)::after {
    display: none;
  }

  .bottom-row {
    flex-direction: column;
    gap: 24px;
  }
}

@media (max-width: 768px) {
  .home-page {
    padding: 16px;
  }

  .search-stats-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .search-stats-toggle {
    width: 100%;
  }
}

@media (max-width: 576px) {
  .stats-cards {
    flex-direction: column;
  }

  .stat-card {
    flex: 1 0 100%;
  }

  .stat-card::after {
    display: none;
  }

  .stat-card {
    padding: 16px;
  }

  .stat-icon {
    width: 48px;
    height: 48px;
  }

  .stat-value {
    font-size: 24px;
  }
}

/* 添加一些动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.main-stats-container {
  animation: fadeIn 0.4s ease-out;
}

.bottom-row .chart-card:nth-child(1) {
  animation: fadeIn 0.4s ease-out 0.1s forwards;
  opacity: 0;
}

.bottom-row .chart-card:nth-child(2) {
  animation: fadeIn 0.4s ease-out 0.2s forwards;
  opacity: 0;
}

/* 优化单选按钮样式 */
:deep(.el-radio-button__inner) {
  padding: 8px 16px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-shadow: none;
  transition: all 0.2s;
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 4px 0 0 4px;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 0 4px 4px 0;
}

:deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background-color: #4080ff;
  border-color: #4080ff;
  box-shadow: none;
}

:deep(.el-radio-button__inner:hover) {
  color: #4080ff;
}
</style>